package org.alys114.springcloud.pbook.controller;

import org.alys114.springcloud.pbook.entity.Book;
import org.alys114.springcloud.pbook.service.BookService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Vincent.chan
 * @date: 2019/9/24 10:31
 * @version: v1.0
 * @Description: TODO<描述>
 */

// 直接@RestController，则表示返回的值都是JSON格式，省去了@ResponseBody的注解
@RestController
@CrossOrigin
public class BookController {
    @Resource
    private BookService bookService;

    @GetMapping("/list")
    public Map list(){
        Map result = new HashMap<>();
        try {
            result.put("code","0");
            result.put("msg","success");
            List<Book> books = bookService.findAll();
            result.put("data",books);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code",e.getClass().getSimpleName());
            result.put("msg",e.getMessage());
        }
        return result;
    }


    @GetMapping("/info")
    public Map info(Integer bid){
        try {
            // 模拟被调用超时
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map result = new HashMap<>();
        try {
            result.put("code","0");
            result.put("msg","success");
            Book book = bookService.getBookByBid(bid);
            result.put("data",book);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code",e.getClass().getSimpleName());
            result.put("msg",e.getMessage());
        }
        return result;
    }

    @RequestMapping("/borrow")
    public Map borrow(Integer bid,String mobile,String takedate,String returndate){
        Date tdate = null;
        Date rdate = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        Map<String, String> result = new HashMap<>();
        result.put("code","0");
        result.put("msg","success");

        try {
            tdate = simpleDateFormat.parse(takedate);
            rdate = simpleDateFormat.parse(returndate);
            bookService.borrow(bid,mobile,tdate,rdate);

        } catch (ParseException e) {
            e.printStackTrace();
            result.put("code",e.getClass().getSimpleName());
            result.put("msg",e.getMessage());
        }
        return result;
    }
}
